<template>
  <el-dialog title="新增角色" :visible="visible" width="500px" @close="onCloseDialog">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" align="left" style="padding-right: 30px;">
      <el-form-item label="角色名称：" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="是否启用：">
        <el-switch v-model="formData.state" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="角色描述：" prop="description">
        <el-input v-model="formData.description" type="textarea" :rows="4" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="margin: 0 40px;" @click="onConfirmAddRole">确定</el-button>
        <el-button @click="onCloseDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { addRoleAPI } from '@/api/role'

const defaultFormData = {
  name: '', // 角色名称
  description: '', // 角色描述
  state: 0 // 是否启用
}

export default {
  name: 'RoleDialog',
  data() {
    return {
      visible: false, // 控制弹窗的显示与隐藏
      formData: { ...defaultFormData }, // 表单数据
      formRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度必须为 2 到 10 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 100, message: '长度必须为 1 到 100 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 打开弹窗
    async open() {
      this.visible = true
    },
    // 关闭弹窗，重置表单
    onCloseDialog() {
      this.visible = false
      this.formData = { ...defaultFormData }
    },
    // 确定新增角色
    onConfirmAddRole() {
      this.$refs.formRef.validate(async isOk => {
        if (isOk) {
          // 发送新增角色请求
          await addRoleAPI(this.formData)
          // 提示操作成功
          this.$message.success('新增角色成功')
          // 发送消息给父组件，以刷新角色列表
          this.$emit('updateRoleList')
          // 关闭弹窗，重置表单
          this.onCloseDialog()
        }
      })
    }
  }
}
</script>

<style>

</style>
